package com.xuecheng.order.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.learning.api.LearningClient;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mappers.OrdersMapper;
import com.xuecheng.order.mappers.PaymentMapper;
import com.xuecheng.order.utils.PayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 定时清理超时订单
 *
 * @author 七安
 */
@Component
public class OrdersTimingJob {

    @Autowired
    private PayUtils payUtils;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private LearningClient learningClient;

    @Scheduled(cron = "0 0/15 * * * ?")
    public void clearingTimeoutOrders() {
        //查询订单超过15风分钟的
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        String date = DateUtil.offsetMinute(new Date(), -15).toString();
        wrapper.lt(Orders::getCreateDate, date);
        List<Orders> ordersList = ordersMapper.selectList(wrapper);
        //判断集合中是否有元素
        if (ordersList.size() <= 0) {
            return;
        }
        for (Orders orders : ordersList) {
            //查询是否支付
            Boolean result = payUtils.checkPayment(orders.getOrderNo());
            //如果支付了
            if (result) {
                //更新支付状态
                orders.setStatus(OrdersConstants.ORDER_PAID_STATUS);
                ordersMapper.updateById(orders);
                //更新支付信息
                LambdaQueryWrapper<Payment> paymentWrapper = new LambdaQueryWrapper<>();
                paymentWrapper.eq(Payment::getOrderNo, orders.getOrderNo());
                Payment payment = paymentMapper.selectOne(paymentWrapper);
                payment.setStatus(OrdersConstants.PAID.toString());
                payment.setPayDate(new Date());
                paymentMapper.updateById(payment);
                //跟新选课计划
                learningClient.saveOrUpdateCourseRec(orders.getCoursePubId(), orders.getUserId());
                //如果没支付
            } else {
                //修改订单状态
                orders.setStatus(OrdersConstants.ORDER_CLOSED_STATUS);
                ordersMapper.updateById(orders);
                //关闭微信接口订单
                payUtils.closeOrder(orders.getOrderNo());
            }
        }
    }
}
